package com.example.demo.controller;

import com.example.demo.model.Friend;
import com.example.demo.model.FriendMapper;
import com.example.demo.model.User;
import com.example.demo.model.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FriendController {
    @Autowired
    private FriendMapper friendMapper;

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/friendList")
    @ResponseBody
    //获取会话需要用到HttpServletRequest参数
    public Object getFriend(HttpServletRequest req){
        //1.先从会话中获取userId
        HttpSession session = req.getSession(false);
        if(session == null){
            //说明用户未登录
            //那么返回一个空的列表
            return new ArrayList<Friend>();
        }
        //获取当前是哪一个用户名登录
        User user = (User) session.getAttribute("user");
        if(user == null){
            return new ArrayList<Friend>();
        }
        //根据userId查好友数据
        List<Friend> ret =
                friendMapper.selectFriendList(user.getUserId());
        return ret;
    }
    //添加好友
    @GetMapping("/addfriends")
    @ResponseBody
    public int addFriend(String friendName, HttpServletRequest req){
        HttpSession session = req.getSession(false);
        User user = (User) session.getAttribute("user");
        int userId = user.getUserId();
        System.out.println(userId);
        int friendId = userMapper.selectByName(friendName).getUserId();
//        System.out.println(friendId);
        //返回3表示添加自己
        if(userId == friendId){
            return 3;
        }

        List<Friend> friends = friendMapper.selectFriendList(userId);
        //不能添加已有好友
        for (int i = 0;i<friends.size();i++){
            if(friends.get(i).getFriendId() == friendId){
                return 2;
            }
        }
//        if(res == true){
//            return 2;
//        }
//        friendMapper.add(userId,friendId);
//        int ret = friendMapper.add(userId,friendId);
        int ret = friendMapper.add(userId,friendId);
        //返回1表示添加好友成功
        if(ret == 2){
            return 1;
        }
        return 10;
    }
}
